<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <div th:replace="common/header :: metaHeader"></div>
  <title>AdminLTE 2 | Data Tables</title>
  <!-- Bootstrap 3.3.6 -->
  <link rel="stylesheet" th:href="@{/static/bootstrap/css/bootstrap.min.css}">
  <link rel="stylesheet" th:href="@{/static/datatables.net/css/jquery.dataTables.min.css}">
  <!-- Font Awesome -->
  <link rel="stylesheet" th:href="@{/static/font-awesome/css/font-awesome.min.css}">
  <!-- Ionicons -->
  <link rel="stylesheet" th:href="@{/static/Ionicons/css/ionicons.min.css}">
  <!-- Theme style -->
  <link rel="stylesheet" th:href="@{/static/admin-lte/css/AdminLTE.min.css}">

    <link rel="stylesheet" th:href="@{/static/datatables.net/Buttons-1.5.6/css/buttons.dataTables.min.css}">
    <link rel="stylesheet" th:href="@{/static/datatables.net/Select-1.3.0/css/select.dataTables.min.css}">
    <link rel="stylesheet" th:href="@{/static/datatables.net/Editor-2019-04-11-1.9.0/css/editor.dataTables.min.css}">
    <link rel="stylesheet" th:href="@{/static/datatables.net/FixedColumns-3.2.5/css/fixedColumns.dataTables.min.css}">

    <!-- AdminLTE Skins. Choose a skin from the css/skins
         folder instead of downloading all of them to reduce the load. -->
  <link rel="stylesheet" th:href="@{/static/admin-lte/css/skins/_all-skins.min.css}">

    <style type="text/css">
        td.details-control {
            background: url('/static/datatables.net/images/details_open.png') no-repeat center center;
            cursor: pointer;
        }
        tr.details td.details-control {
            background: url('/static/datatables.net/images/details_close.png') no-repeat center center;
        }
    </style>

  <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
  <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
  <!--[if lt IE 9]>
  <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
  <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
  <![endif]-->
</head>
<body class="hold-transition skin-blue sidebar-mini">
<!-- Content Header (Page header) -->
<section class="content-header">
    <h1>
        Table
        <small>Version 2.0</small>
    </h1>
    <ol class="breadcrumb">
        <li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
        <li class="active">Dashboard</li>
    </ol>
</section>

<!-- Main content -->
<section class="content">
    <div class="box">
        <div class="box-header">
            <h3 class="box-title">Data Table With Full Features</h3>
        </div>
        <a class="editor_create">Create new record</a>
        <!-- /.box-header -->
        <div class="box-body">
            <table id="example1" class="table table-bordered table-striped">
                <thead>
                <tr>
                    <th></th>
                    <th>No.</th>
                    <th>Rendering engine</th>
                    <th>Browser</th>
                    <th>Platform(s)</th>
                    <th>Engine version</th>
                    <th>edit</th>
                </tr>
                </thead>
            </table>
        </div>
        <!-- /.box-body -->
    </div>
    <!-- /.box -->
</section>
<!-- /.content -->

<!-- jQuery -->
<script th:src="@{/static/jquery/jquery.min.js}"></script>
<!-- Bootstrap 3.3.6 -->
<script th:src="@{/static/bootstrap/js/bootstrap.min.js}"></script>
<script th:src="@{/static/datatables.net/js/datatables.min.js}"></script>
<script th:src="@{/static/datatables.net/js/jquery.dataTables.min.js}"></script>

<script th:src="@{/static/datatables.net/Buttons-1.5.6/js/dataTables.buttons.min.js}"></script>
<script th:src="@{/static/datatables.net/Select-1.3.0/js/dataTables.select.min.js}"></script>
<script th:src="@{/static/datatables.net/Editor-2019-04-11-1.9.0/js/dataTables.editor.min.js}"></script>
<script th:src="@{/static/datatables.net/FixedColumns-3.2.5/js/dataTables.fixedColumns.min.js}"></script>
<script>
    function format ( d ) {
        return 'Full name: '+d.username+' '+'<br>'+
            'password: '+d.password+'<br>'+
            'The child row can contain any data you wish, including links, images, inner tables etc.';
    }

  //https://datatables.net/reference/option/
  var dataTable1, editor1;
  $(function () {
    editor1 = new $.fn.dataTable.Editor({
        //默认crud操作，post到该接口，然后action=create/delete/edit
        "ajax": {//自定义请求参数
            "url": "/table/update",
            "type": "POST",
            "data": function (d) {
                        //console.log(d);
                        //自定义附加参数
                        d._csrf = "[[${_csrf.token}]]";
                        d.my_key = "my_value";
                        return d;
                    }
            /**
            可以自定义每个操作的api接口
            create: {
                type: 'POST',
                url:  '../php/rest/create.php'
            },
            edit: {
                type: 'PUT',
                url:  '../php/rest/edit.php?id=_id_'
            },
            remove: {
                type: 'DELETE',
                url:  '../php/rest/remove.php?id=_id_'
            }
            **/
        },
        "table": "#example1",
        //编辑器要求必须存在唯一表示字段https://datatables.net/manual/tech-notes/14，也可以在datatables定义DT_RowId
        "idSrc":  "id",
        "fields": [ {
                "label": "用户名:",
                "name": "username",
                "def": function () { return "username"; }
            }, {
                "label": "密码:",
                "name": "password",
                "def": "123"
            }, {
                "label": "状态:",
                "name": "enabled",
                "type":  "radio",
                "options" : [
                    { label: "启用", value: "1" },
                    { label: "禁用",  value: "0" }
                ],
                "def": "1"
            }
        ]
    });
    dataTable1 = $('#example1').DataTable({
      "autoWidth" : true,
      "deferRender" : true,
      "scrollY" : "60vh",
      //左边3行固定,依赖dataTables.fixedColumn.js
      //"fixedColumns": {
      //      leftColumns: 3
      //  },
      //"scrollX": true,
      //允许降低表高度
      "scrollCollapse": true,
      "responsive" : true,
      "select" : true,
      //cookie缓存分页信息
      "stateSave": false,
      "processing": true,
      "serverSide": true,
      //调用地址
      "ajax": {//自定义请求参数
            "url": "/table/data",
            "type": "POST",
            "data": function (d) {
                        //console.log(d);
                        //自定义附加参数
                        d._csrf = "[[${_csrf.token}]]";
                        d.my_key = "my_value";
                        return d;
                    }
            },
        //返回的json列映射
        "columns" : [
                    {//详情图标按钮
                        "class":          "details-control",
                        "orderable":      false,
                        "data":           null,
                        "defaultContent": ""
                    },
                    {//序号
                        "data": null
                    },
                    {
                        "data" : "id",
                    },
                    {
                        "data" : "username",
                        "title" : "用户名"
                    }, {
                        "data" : "password",
                        "title" : "密码"
                    }, {
                        "data" : "enabled",
                        "title" : "状态",
                        "render": function(d,type,row) {
                            if (d.enabled == true)
                                return '启用';
                            else
                                return '禁用';
                        }
                    }, {
                        "data" : null,
                        "title" : "编辑"
                    }
                    ],
        "columnDefs": [
            {//第3列不可见，id列
                "targets": [2],
                "visible": false,
                "searchable": false
            },
            {//最后一列增加编辑按钮
            "targets": -1,
            "data": null,
            "defaultContent": "<a href='' class='editor_edit'>Edit</a> / <a href='' class='editor_remove'>Delete</a>"
            }
        ],
        //排序
        "order": [
                    [3, 'asc']
                 ],
        //语言
        "language": {
            "lengthMenu": "每页 _MENU_ 条",
            "zeroRecords": "暂无记录哦~",
            "info": "第 _PAGE_ / _PAGES_ 页",
            "infoEmpty": "什么都没有",
            "infoFiltered": "(共找到 _MAX_ 记录)",
            "info":         "从 _START_ 到 _END_ 共 _TOTAL_ 条数据",
            "search":         "搜索:",
            "emptyTable":     "No data available in table",
            "loadingRecords": "Loading...",
            "processing":     "Processing...",
            "paginate": {
                "first":      "第一页",
                "last":       "最后一页",
                "next":       "下一页",
                "previous":   "前一页"
            },
            "aria": {
                "sortAscending":  ": 升序排列",
                "sortDescending": ": 降序排列"
            }
        }
    });

      // New record
    $('a.editor_create').on('click', function (e) {
        e.preventDefault();
        editor1.create( {
            title: 'Create new record',
            buttons: 'Add'
        } );
    } );

    // Edit record
    $('#example1 tbody').on('click', 'tr td a.editor_edit', function (e) {
        //console.log($(this).closest('tr'));
        e.preventDefault();
        //console.log($(this).closest('tr'));
        editor1.edit($(this).closest('tr'), {
            title: '编辑',
            buttons: 'Update'
        });
    });

    // Delete a record
    $('#example1 tbody').on('click', 'tr td a.editor_remove', function (e) {
        e.preventDefault();
        editor1.remove( $(this).closest('tr'), {
            title: '删除',
            message: '确认删除该记录?',
            buttons: '确认'
        });
    });

    //详情图标点击事件
    var detailRows = [];
   $('#example1 tbody').on('click','tr td.details-control', function (e) {
        var tr = $(this).closest('tr');
        var row = dataTable1.row( tr );
        var idx = $.inArray( tr.attr('id'), detailRows);
        console.log(idx);// idx是0，-1来回变动
        //detailRows是个array,存储的0和无数据
        console.log(detailRows);
        if ( row.child.isShown() ) {
            tr.removeClass( 'details' );
            row.child.hide();
            // Remove from the 'open' array
            detailRows.splice( idx, 1 );
        }
        else {
            tr.addClass( 'details' );
            row.child( format( row.data() ) ).show();
            // Add to the 'open' array
            if ( idx === -1 ) {
                detailRows.push( tr.attr('id') );
            }
        }
     });
     //增加序号列，draw重绘事件
     dataTable1.on('draw', function () {
            //保证分页情况下序号连续
            var pageInfo = dataTable1.page.info();
            dataTable1.column(1, { page: 'current' }).nodes().each( function (cell, i) {
                cell.innerHTML = i + 1 + pageInfo.start;
                //td元素
                //console.log(cell);
            });
            //样式绑定点击事件
            $.each(detailRows, function (i, id) {
                console.log(i);//索引
                console.log(id);//空串或者上面push进去的0
                $('#'+id+' td.details-control').trigger( 'click' );
            });
     });

  });
</script>
</body>
</html>
